﻿Imports System.Data.SqlClient
Imports System.Net.Mail
Partial Class cna
    Inherits System.Web.UI.Page

    Public membershipConnectionString As String = ConfigurationManager.ConnectionStrings("FSEMembershipConnection").ConnectionString
   

    

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Request.IsAuthenticated = True Then
            Response.Redirect("Home.aspx")
            Exit Sub
        End If

        If IsPostBack Then
            statuslabel.Visible = False
        End If

    End Sub

    Protected Sub cna2continuebuttonlink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cna2continuebuttonlink.Click
        statuslabel.Visible = False
        Dim tryDomain As String
        Dim Domain As String = Nothing
        Dim i As Integer, k As Integer = Nothing, j As Integer
        Dim memStatus As MembershipCreateStatus
        Dim conn As New SqlConnection(membershipConnectionString)


        i = InStr(1, cna2emailbox.Text, "@", CompareMethod.Text)
        j = Len(cna2emailbox.Text) - i
        tryDomain = Right(cna2emailbox.Text, j)


        Dim queryString As String = "SELECT [domain] from [UniversityDetails] where [University_ID] = " & cna2university.SelectedIndex
        Dim cmd As New SqlCommand(queryString, conn)





        conn.Open()
        Dim reader As SqlDataReader = cmd.ExecuteReader
        While reader.Read()
            Domain = reader("domain").ToString
        End While



        conn.Close()

        If Trim(tryDomain) <> Trim(Domain) Then
            statuslabel.Visible = True
            statuslabel.Text = "The email domain does not match the selected university. Click " & _
            "<a href='home.aspx'>here</a> for more info."
        Else


            Try
                Dim newUser As MembershipUser = _
                    Membership.CreateUser( _
                    username:=cna2usernamebox.Text, _
                    password:=cna2passwordbox.Text, _
                    email:=cna2emailbox.Text)

                newUser.IsApproved = False

                insertDetails( _
                newUser:=newUser, _
                fname:=cna2fname.Text, _
                lname:=cna2lname.Text, _
                secondemail:=cna2secondaryemail.Text, _
                showemail:=cna2showemailcheckbox.Checked, _
                universityID:=cna2university.SelectedIndex, _
                city:=cna2citybox.Text, _
                state:=cna2statebox.Text, _
                majorID:=cna2majorbox.SelectedIndex, _
                minorID:=cna2minorbox.SelectedIndex)

                If Membership.ValidateUser(cna2usernamebox.Text, cna2passwordbox.Text) Then
                    'Send a confirmation email to the address provided
                    Dim email As String = cna2emailbox.Text
                    Dim name As String = cna2fname.Text
                    Dim mail As MailMessage = New MailMessage()
                    Dim myGuid As Guid = CType(newUser.ProviderUserKey, Guid)



                    mail.To.Add(cna2emailbox.Text) 'change this to email variable
                    mail.From = New MailAddress("donotreply@freestudentexchange.com")
                    mail.Subject = "Email Verification - Free Student Exchange"

                    Dim Body As String = name & ", <br><br> <p>This email is to confirm your Free Student Exchange account created for " & email & ". <br>" & _
                    "<br><a href='http://localhost:54164/Free%20Student%20Exchange%203/Members/confirm.aspx?id=" & myGuid.ToString() & "'>Click here to " & _
                    "verify your email address</a></p><br><br><p>If you are having trouble clicking the above link, copy the following link and paste " & _
                    "it into your browser's address bar:<br><br>http://localhost:54164/Free%20Student%20Exchange%203/Members/confirm.aspx?id=" & myGuid.ToString() & _
                    "</p><br><hr><p style='font-size:10;color:#787b7c;'>If you have any questions, please visit our help page at " & _
                    "<a href='http://www.freestudentexchange.com/help'>www.FreeStudentExchange.com/Help.aspx</a> or contact us at feedback@freestudentexchange.com</p>"

                    mail.Body = Body
                    mail.IsBodyHtml = True

                    Dim smtp As SmtpClient = New SmtpClient()
                    smtp.Host = "smtp.gmail.com"
                    smtp.Port = 587
                    smtp.Credentials = New System.Net.NetworkCredential("fse.4testing9249@gmail.com", "fsetesting435")
                    smtp.EnableSsl = True
                    smtp.Send(mail)

                    FormsAuthentication.RedirectFromLoginPage(cna2usernamebox.Text, False)
                Else

                    MsgBox("FSE encountered an unexpected error. Please try again later.")
                    Server.Transfer("Home.aspx")
                End If


            Catch ex As MembershipCreateUserException
                statuslabel.Visible = True
                statuslabel.Text = GetErrorMessage(ex.StatusCode)
            Catch ex As HttpException
                statuslabel.Text = ex.Message
            End Try

        End If



       

    End Sub

    Protected Sub insertDetails(ByRef newUser As MembershipUser, ByRef fname As String, ByRef lname As String, _
                                ByRef secondemail As String, ByRef showemail As Boolean, _
                                ByRef universityID As Integer, ByRef city As String, ByRef state As String, _
                                ByRef majorID As Integer, ByRef minorID As Integer)

        Dim i As Integer, j As Integer, k As Integer
        Dim conn2 As New SqlConnection(membershipConnectionString)
        Dim cmd2 As New SqlCommand
        Dim queryString As String
        Dim showemailint As Integer

        i = 0
        j = 0
        k = 0

        If showemail = True Then
            showemailint = 1
        Else
            showemailint = 0
        End If

        Dim newUserId As Guid = CType(newUser.ProviderUserKey, Guid)


        conn2.Open()
        cmd2.Connection = conn2

        queryString = "INSERT INTO UserProfiles (UserId, firstname, lastname, secondemail, showemail, universityID, city, state, majorID, minorID) " & _
        "VALUES (@UserId, '" & fname & "', '" & lname & "', '" & secondemail & "', '" & showemailint & "', '" & universityID & "', '" & _
        city & "', '" & state & "', '" & majorID & "', '" & minorID & "')"


        cmd2.CommandText = queryString
        cmd2.Parameters.AddWithValue("@UserId", newUserId)
        cmd2.ExecuteNonQuery()
        conn2.Close()

    End Sub

    Public Function GetErrorMessage(ByVal status As MembershipCreateStatus) As String
        Select Case status
            Case MembershipCreateStatus.DuplicateUserName
                Return "**Username already exists."
            Case MembershipCreateStatus.InvalidPassword
                Return "**Password must be at least eight characters and include at least one number."
            Case MembershipCreateStatus.InvalidEmail
                Return "**That email is already in use by another user."
            Case Else
                Return "An unknown error occurred. The account was not created. If the problem persists, please contact our " & _
                "<a href='cna2.aspx'>system administrator</a>."
        End Select

    End Function

    

End Class
